<?php

namespace loggedin\model;

require_once("/loggedin/model/Question.php");

class AddQuestion {
	/**
	 * @param  loggedin\model\Question $question
	 * @throws Exception om någon av inmatningarna är för korta.
	 */
	public function validateNewQuestion(\loggedin\model\Question $question) {
		if(strlen($question->getQuestion()) < 10) {
			throw new \Exception("1");
		}
		if(strlen($question->getRightAnswer()) < 0) {
			throw new \Exception("2");
		}
		if(strlen($question->getWrongAnswer1()) < 0) {
			throw new \Exception("3");
		}
		if(strlen($question->getWrongAnswer2()) < 0) {
			throw new \Exception("4");
		}
		if(strlen($question->getWrongAnswer3()) < 0) {
			throw new \Exception("5");
		}
		if(strlen($question->getQuestion()) != strip_tags($question->getQuestion())){
			throw new Exception("6");
		}
		if(strlen($question->getRightAnswer()) != strip_tags($question->getRightAnswer())){
			throw new Exception("6");
		}
		if(strlen($question->getWrongAnswer1()) != strip_tags($question->getWrongAnswer1())){
			throw new Exception("6");
		}
		if(strlen($question->getWrongAnswer2()) != strip_tags($question->getWrongAnswer2())){
			throw new Exception("6");
		}
		if(strlen($question->getWrongAnswer3()) != strip_tags($question->getWrongAnswer3())){
			throw new Exception("6");
		}
	}

	/**
	 * @param string                $username
	 * @param loggedin\model\Question $question
	 * @param mysqli                $mysqli
	 * @throws Exception om något med databasen inte fungerar.
	 */
	public function addToDatabase($username, \loggedin\model\Question $question, \mysqli $mysqli) {
		$sqlQ = "INSERT INTO `Questions` (`Username`, `Question`, `RightAnswer`,
										  `WrongAnswer1`, `WrongAnswer2`, `WrongAnswer3`)
				VALUES(?, ?, ?, ?, ?, ?)";
		$stmt = $mysqli->prepare($sqlQ);
		if($stmt == false) {
			throw new \Exception("Prepare of sql question failed" . $mysqli->error);
		}
		$questionString = $question->getQuestion();
		$rightAnswer = $question->getRightAnswer();
		$wrongAnswer1 = $question->getWrongAnswer1();
		$wrongAnswer2 = $question->getWrongAnswer2();
		$wrongAnswer3 = $question->getWrongAnswer3();

		$res = $stmt->bind_param("ssssss", $username, $questionString, $rightAnswer, $wrongAnswer1,
								 $wrongAnswer2, $wrongAnswer3);
		if ($res == false) {
			throw new \Exception("Bind param failed " . $stmt->error);
		}
		$res = $stmt->execute();
		if($res == false) {
			throw new \Exception("Database execute failed " . $stmt->error);
		}
	}
}